﻿using LbangCMS.Areas.Admin.Models;
using LbangCMS.EFModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LbangCMS.Areas.Admin.Controllers
{
    public class UploadController : Controller
    {
        public ActionResult Upload()
        {
            return View();
        }

        private List<Image> GetImageList(out int totalPage,int pageIndex = 1, int pageSize = 20)
        {
            using (var db = new Database())
            {
                var count = db.Images.Count();
                totalPage =(int) Math.Ceiling(count / (pageSize*1M));
                return db.Images.OrderByDescending(o=>o.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
        }
        public ActionResult ImageList(int pageIndex = 1, int pageSize = 20)
        {
            var model = new ImageLisModel();
            model.PictureList = new List<ImageModel>();
            int totalPage;
            var pictures = GetImageList(out totalPage,pageIndex, pageSize);
            if (pictures != null && pictures.Any())
            {
                model.TotalPage = totalPage;
                if (pageIndex > totalPage)
                    pageIndex = totalPage;
                model.CurrentPageIndex = pageIndex;
                pictures.ForEach(o => model.PictureList.Add(new ImageModel { Id = o.ID, FileName = o.FileName, FilePath = o.FilePath,  }));
            }
            else
            {
                model.CurrentPageIndex = 1;
                model.TotalPage = 0;
            }
            if (Request.IsAjaxRequest())
            {
                return PartialView("_ImageListPartial", model);
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult ImageUpload(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
        {

            string filePathName = string.Empty;
            var dirtory = Server.MapPath("~/uploads");
            string localPath = Path.Combine(dirtory, "pictures");
            if (Request.Files.Count == 0)
            {
                return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失败" }, id = "id" });
            }
            string ex = Path.GetExtension(file.FileName);
            if (!IsImageExtensionName(ex))
            {
                return Json(new { jsonrpc = 2.0, error = new { code = 500, message = "非图片文件" }, id = "id" });
            }
            filePathName = Guid.NewGuid().ToString("N") + ex;
            if (!System.IO.Directory.Exists(localPath))
            {
                System.IO.Directory.CreateDirectory(localPath);
            }
            var filePath = "/uploads/pictures/" + filePathName;
            file.SaveAs(Path.Combine(localPath, filePathName));
            AddImage(filePath,name);
            return Json(new
            {
                jsonrpc = "2.0",
                id = id,
                filePath = filePath
            });
        }



        private bool IsImageExtensionName(string ex)
        {
            ex = ex.ToLower();
            if (ex == ".jpg" || ex == ".jpeg" || ex == ".png" || ex == ".bmp" || ex == ".gif")
                return true;
            else
                return false;
        }

        public void AddImage(string filePath,string name)
        {
            using (var db = new Database())
            {
                var image = new Image();
                image.FileName = name;
                image.FilePath = filePath;
                db.Images.Add(image);
                db.SaveChanges();
            }
        }

        public ActionResult RemovePicture(int id)
        {
            using (var db = new Database())
            {
                var image = db.Images.Where(o => o.ID == id).FirstOrDefault();
                if(image!=null)
                {
                    db.Images.Remove(image);
                    db.SaveChanges();
                }
            }
            return Json(new { success = true });
        }
    }
}